using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace mjjames.WebControls
{
	[ToolboxData("<{0}:jQuery runat=server></{0}:jQuery>")]
	public class jQuery : WebControl
	{
		string _sVersion = "1.2.0";
		string _sType = "";
		string _sPath = "/javascript/";
		string[] _aTypes = new string[3] { "", "min", "pack" };
		
		string _sControlExists = "false";		

/// <summary>
/// Allows you to specify which jQuery version you want, normal, min, packed - includes a basic check to ensure we dont try to load an invalid type
/// </summary>
		public string Type
		{
			get { return _sType; }
			set { 
				for(int i = 0; i < _aTypes.Length; i++){
					if(value.ToLower() == _aTypes[i])
					{
						_sType = value; 
					}
				}
			}
		}
/// <summary>
/// Allows you to specify the location of the jQuery files
/// </summary>
		
		public string Path
		{
			get { return _sPath; }
			set { _sPath = value; }
		}
		
/// <summary>
/// Specifies the version of jQuery to load 1.2.2 etc
/// </summary>
		public string Version
		{
			get { return _sVersion; }
			set { _sVersion = value; }
		}
		
/// <summary>
/// render method
/// </summary>
/// <param name="output"></param>
		protected override void Render(System.Web.UI.HtmlTextWriter output)
		{
			if (HttpContext.Current.Items.Contains("jQueryRendered"))
			{
				_sControlExists = (string)HttpContext.Current.Items["jQueryRendered"]; //.ToString();
			}
			if( _sControlExists.Contains("false")){
				string sFile = "";
				if (_sType.Length > 0){
					_sType += ".";
				}
				sFile = _sPath + "jquery-" + _sVersion + "." + _sType + "js";
				output.Write(string.Format("<script src=\"{0}\" type=\"text/javascript\"></script>\r\n",sFile));
				HttpContext.Current.Items.Add("jQueryRendered", "true");
			}
		}
	}
}
